package com.wang.project.utils;

import cn.hutool.crypto.SecureUtil;
import com.wang.project.constant.CommonConstant;
import com.wang.project.model.entity.User;
import com.wang.project.model.file.FileUploadParam;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtils {

    /**
     * 编码文件名
     * 用途 + 用户名的加密 -> type + userAccount
     * 示例：fileName=userAvatar_admin.jpg
     * 用户的userAccount字段是唯一的，不允许重复的
     */
    public static final String getMinioUploadFileName(FileUploadParam param, User user) {
        String userAccountStr = DigestUtils.md5DigestAsHex((CommonConstant.SALT + user.getUserAccount()).getBytes());
        String fileName = param.getType() + "_" + param.getRegion() + "_" + userAccountStr;
        return fileName;
    }

    public static final String getMinioUploadFileNameByRegionName(FileUploadParam param, String regionName) {
        String userAccountStr = DigestUtils.md5DigestAsHex((CommonConstant.SALT + regionName).getBytes());
        String fileName = param.getType() + "_" + param.getRegion() + "_" + userAccountStr;
        return fileName;
    }

    public static final String getMinioUploadFileNameByInterfaceName(FileUploadParam param, String interfaceName) {
        String userAccountStr = DigestUtils.md5DigestAsHex((CommonConstant.SALT + interfaceName).getBytes());
        String fileName = param.getType() + "_" + param.getRegion() + "_" + userAccountStr;
        return fileName;
    }

    /**
     * 根据文件的在线地址，获取url中的文件name
     * 如：user_avatar_299da5bf38b3592a75689305dd87ef47.jpg
     *
     * @param url
     * @return
     */
    public static final String getFileNameByUrl(String url) {
        Pattern pattern = Pattern.compile(".*/([^/?]+).*");
        Matcher matcher = pattern.matcher(url);
        if (matcher.matches()) {
            String fileName = matcher.group(1);
            return fileName;
        }

        return null; // 如果无法匹配或提取文件名，则返回 null
    }


    /**
     * 编码文件名
     * 日期路径 + UUID
     * 示例：fileName=2022/11/18/统计报表1668758006562.txt
     */
    public static final String extractUploadFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        // 注意，这里需要加上 \\ 将 特殊字符 . 转意 \\. ,否则异常
        String[] fileArray = fileName.split("\\.");
        fileName = datePath() + "/" + fileArray[0] + System.currentTimeMillis() + "." + fileArray[1];
        return fileName;
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }
}